package com.ikas.ai.utils;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ReflectUtil;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description: 对象进行类型转换
 * @Author: qi.yilai
 * @Date: 2022/3/11 14:23
 * @Version: 1.0.0
 **/
public class BeanUtils {
    private static Logger logger = LoggerFactory.getLogger(BeanUtils.class);

    /**
     * 类型转换
     *
     * @param source
     * @param clazz
     * @param <T>
     * @return
     * @throws Exception
     */
    public static <T> T convert(Object source, Class<T> clazz) {
        T t = null;
        try {
            t = clazz.newInstance();
        } catch (InstantiationException e) {
            logger.error("new instance error", e);
        } catch (IllegalAccessException e) {
            logger.error("access error", e);
        }
        org.springframework.beans.BeanUtils.copyProperties(source, t);
        return t;
    }

    /**
     * 批量类型转换
     *
     * @param collection
     * @param clazz
     * @param <T>
     * @return
     * @throws Exception
     */
    public static <T> List<T> convert(Collection collection, Class<T> clazz) {
        if (CollectionUtils.isEmpty(collection)) {
            return Lists.newArrayList();
        }

        List<T> list =  (List<T>)collection.stream().map(source -> {
            try {
                return BeanUtils.convert(source, clazz);
            } catch (Exception e) {
                return null;
            }
        }).filter(source -> {return Objects.nonNull(source);}).collect(Collectors.toList());
        return list;
    }

    /**
     * 复制对象方法 - 忽略错误
     *
     * @param source 源对象
     * @param tClass 目标类
     * @return R 结果
     * @author ly
     */
    public static <T, R> R copy(T source, Class<R> tClass) {
        R target = ReflectUtil.newInstanceIfPossible(tClass);
        BeanUtil.copyProperties(source, target, CopyOptions.create().ignoreError());
        return target;
    }
}
